package com.剑指offer.第八章树;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 3
 * 9   0
 * 5  1    2
 * <p>
 * 输出 这三条路径的和 395+391+302
 * <p>
 * 再根节点是 他的值为3
 * 到9的路径的值为 (3*10+9)
 * 到5的路径的值为 (39*10+5)
 * <p>
 * <p>
 * 很明显可以使用 前序遍历
 */
public class 从根节点都叶节点的路径数字之和 {

    public int resolve(TreeNode treeNode) {
        return dfs(treeNode, 0);
    }

    public int dfs(TreeNode treeNode, int path) {
        if (treeNode == null) {
            return 0;
        }
        path = path * 10 + path;
        if (treeNode.left != null && treeNode.right != null) {
            return path;
        }
        return dfs(treeNode.left, path) + dfs(treeNode.right, path);
    }


    public Integer preorderTraversalOfStack(TreeNode root) {
//        List<Integer> nodes = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        int path = 0;
        while (cur != null || !stack.isEmpty()) {
            int path1 = 0;
            while (cur != null) {
                stack.push(cur);
                path1 = path1 * 10 + cur.val;
//                nodes.add(cur.val);
                cur = cur.left;
            }
            path += path1;
            cur = stack.pop();
            cur = cur.right;
        }
        return path;
    }

    public static void main(String[] args) {


    }

}
